package Iterator;

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ArrayListParallelSpliteratorExample {
    public static void main(String[] args) {
        // 创建一个包含整数的 ArrayList
        List<Integer> numbers = new ArrayList<>();
        for (int i = 1; i <= 20; i++) {
            numbers.add(i);
        }

        // 获取 ArrayList 的 spliteratorOne
        Spliterator<Integer> spliteratorOne = numbers.spliterator();
        // 使用 trySplit() 方法拆分 spliteratorTwo
        Spliterator<Integer> spliteratorTwo = spliteratorOne.trySplit();

        // 定义一个处理元素的 Consumer
        java.util.function.Consumer<Integer> action = (Integer number) ->
                System.out.println("当前线程: " + Thread.currentThread().getName() + " 处理数字: " + number);
        // 使用第一个 Spliterator 进行遍历
        /*System.out.println("使用第一个 Spliterator 进行遍历:");
        spliteratorOne.forEachRemaining(action);
        // 使用拆分后的 Spliterator 进行遍历
        System.out.println("\n使用拆分后的 Spliterator 进行遍历:");
        if (spliteratorTwo != null) {
            spliteratorTwo.forEachRemaining(action);
        }*/
        //
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2,2,0,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(1),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 2; i++) {
            executor.execute(() -> {
                spliteratorOne.forEachRemaining(action);
                spliteratorTwo.forEachRemaining(action);
            });
        }
    }
}